#include "lvgl/lvgl.h"
#include "lvgl/demos/lv_demos.h"
#include "lv_drivers/display/fbdev.h"
#include "lv_drivers/indev/evdev.h"
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h>

#include "./../../inc/login.h"
#include "./../../inc/tcp.h"
#include "./../../inc/msg_popup.h"
#include "../inc/cJSON.h"
#include "../inc/user_event.h"
#include "../inc/homepage.h"

static int clicked              = 0;
static uint32_t last_click_time = 0;
static lv_obj_t * username_ta   = NULL;
static lv_obj_t * password_ta   = NULL;
static lv_obj_t * username_ta1  = NULL;
static lv_obj_t * password_ta1  = NULL;

lv_obj_t * register_popup     = NULL;
lv_obj_t * login_src          = NULL;
lv_obj_t * connted_title_card = NULL;
lv_obj_t * connted_title      = NULL;

const char * username = NULL;
const char * password = NULL;

static void close_login_event(lv_event_t * e);
static void register_btn_event(lv_event_t * e);
static void close_register_event(lv_event_t * e);
static void login_btn_event(lv_event_t * e);
static void confirm_btn_event(lv_event_t * e);
static char * build_json_request(const char * cmd_type, const char * username, const char * password);

void login_init()
{
    if(login_src != NULL) {
        lv_obj_clear_flag(login_src, LV_OBJ_FLAG_HIDDEN); // 显示界面
        return;
    }
    login_src = lv_obj_create(lv_scr_act());
    lv_obj_set_size(login_src, LV_HOR_RES, LV_VER_RES);
    lv_obj_set_style_radius(login_src, 0, 0);
    lv_obj_set_style_border_width(login_src, 0, 0);
    lv_obj_clear_flag(login_src, LV_OBJ_FLAG_SCROLLABLE); // 不可滚动

    lv_obj_t * bg = lv_img_create(login_src);
    lv_img_set_src(bg, "S:./res/ui/login_bg.png");
    lv_obj_center(bg);

    // 创建登录窗口
    lv_obj_t * login = lv_obj_create(login_src);
    lv_obj_set_size(login, 400, 300);
    lv_obj_set_style_radius(login, 12, 0);
    lv_obj_set_style_bg_color(login, lv_color_white(), 0);
    lv_obj_set_style_bg_opa(login, LV_OPA_100, 0);
    lv_obj_set_style_border_width(login, 0, 0);
    lv_obj_center(login);

    // 添加标题
    lv_obj_t * title = lv_label_create(login);
    lv_label_set_text(title, "登录");
    lv_obj_set_style_text_color(title, lv_color_make(0, 0, 0), 0);
    lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 10);
    LV_FONT_DECLARE(SourceHanSansCN_Bold_20);
    lv_obj_set_style_text_font(title, &SourceHanSansCN_Bold_20, LV_PART_MAIN | LV_STATE_DEFAULT);

    // 用户名输入框容器
    lv_obj_t * username_cont = lv_obj_create(login);
    lv_obj_set_size(username_cont, 300, 50);
    lv_obj_set_style_bg_opa(username_cont, LV_OPA_0, 0);
    lv_obj_set_style_border_width(username_cont, 0, 0);
    lv_obj_set_style_pad_all(username_cont, 0, 0);
    lv_obj_align(username_cont, LV_ALIGN_TOP_MID, 0, 60);
    lv_obj_clear_flag(username_cont, LV_OBJ_FLAG_SCROLLABLE); // 不可滚动

    // 创建图标
    lv_obj_t * username_icon = lv_img_create(username_cont);
    lv_img_set_src(username_icon, "S:res/ui/username.png");
    lv_obj_set_size(username_icon, 48, 48);
    lv_obj_set_pos(username_icon, 2, 2);

    // 创建输入框
    username_ta = lv_textarea_create(username_cont);
    lv_obj_set_size(username_ta, 250, 48);                                      // 宽度调整
    lv_obj_align_to(username_ta, username_icon, LV_ALIGN_OUT_RIGHT_MID, 10, 0); // 在图标右边10px
    lv_obj_set_style_radius(username_ta, 6, 0);
    lv_obj_set_style_border_width(username_ta, 1, 0);
    lv_obj_set_style_border_color(username_ta, lv_color_hex(0xCCCCCC), 0);
    lv_obj_set_pos(username_ta, 50, 0);
    lv_textarea_set_max_length(username_ta, 20); // 最大长度

    // 密码输入框容器
    lv_obj_t * password_cont = lv_obj_create(login);
    lv_obj_set_size(password_cont, 300, 50);
    lv_obj_set_style_bg_opa(password_cont, LV_OPA_0, 0);
    lv_obj_set_style_border_width(password_cont, 0, 0);
    lv_obj_set_style_pad_all(password_cont, 0, 0);
    lv_obj_align(password_cont, LV_ALIGN_TOP_MID, 0, 130);
    lv_obj_clear_flag(password_cont, LV_OBJ_FLAG_SCROLLABLE); // 不可滚动

    lv_obj_t * password_icon = lv_img_create(password_cont);
    lv_img_set_src(password_icon, "S:res/ui/password.png");
    lv_obj_set_size(password_icon, 48, 48);
    lv_obj_set_pos(password_icon, 2, 2);

    password_ta = lv_textarea_create(password_cont);
    lv_obj_set_size(password_ta, 250, 48);
    lv_obj_align_to(password_ta, password_icon, LV_ALIGN_OUT_RIGHT_MID, 10, 0); // 在图标右边10px
    lv_obj_set_style_radius(password_ta, 6, 0);
    lv_obj_set_style_border_width(password_ta, 1, 0);
    lv_obj_set_style_border_color(password_ta, lv_color_hex(0xCCCCCC), 0);
    lv_obj_set_pos(password_ta, 50, 0);
    lv_textarea_set_max_length(password_ta, 20);

    // 登录按钮
    lv_obj_t * login_btn = lv_btn_create(login);
    lv_obj_set_size(login_btn, 80, 45);

    lv_obj_align(login_btn, LV_ALIGN_BOTTOM_MID, 100, -10);
    lv_obj_set_style_radius(login_btn, 8, 0);
    lv_obj_set_style_bg_color(login_btn, lv_color_hex(0x2196F3), 0);

    // 登录按钮文本​
    lv_obj_t * login_label = lv_label_create(login_btn);
    lv_label_set_text(login_label, "登录");
    lv_obj_set_style_text_color(login_label, lv_color_white(), 0);
    LV_FONT_DECLARE(SourceHanSansCN_Bold_20);
    lv_obj_set_style_text_font(login_label, &SourceHanSansCN_Bold_20, LV_PART_MAIN | LV_STATE_DEFAULT);
    lv_obj_center(login_label);

    // 注册按钮
    lv_obj_t * register_btn = lv_btn_create(login);
    lv_obj_set_size(register_btn, 80, 45);

    lv_obj_align(register_btn, LV_ALIGN_BOTTOM_MID, -100, -10);
    lv_obj_set_style_radius(register_btn, 8, 0);
    lv_obj_set_style_bg_color(register_btn, lv_color_hex(0x4CAF50), 0);

    // 注册按钮文本
    lv_obj_t * register_label = lv_label_create(register_btn);
    lv_label_set_text(register_label, "注册");
    LV_FONT_DECLARE(SourceHanSansCN_Bold_20);
    lv_obj_set_style_text_font(register_label, &SourceHanSansCN_Bold_20, LV_PART_MAIN | LV_STATE_DEFAULT);
    lv_obj_set_style_text_color(register_label, lv_color_white(), 0);
    lv_obj_center(register_label);

    // 添加键盘
    kb = lv_keyboard_create(login_src);
    lv_obj_set_size(kb, LV_HOR_RES, LV_VER_RES / 2);
    lv_obj_align(kb, LV_ALIGN_BOTTOM_MID, 0, 20);
    lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN); // 初始隐藏

    // 为文本框添加事件回调
    lv_obj_add_event_cb(username_ta, ta_event_cb, LV_EVENT_ALL, kb);
    lv_obj_add_event_cb(password_ta, ta_event_cb, LV_EVENT_ALL, kb);

    // // 添加事件
    lv_obj_add_event_cb(login_btn, login_btn_event, LV_EVENT_CLICKED, login_src);
    lv_obj_add_event_cb(register_btn, register_btn_event, LV_EVENT_CLICKED, login_src);

    // show_network_connection_title(login_src);
}

void register_init(lv_obj_t * parent)
{
    // 创建半透明背景层
    register_popup = lv_obj_create(parent);
    lv_obj_set_size(register_popup, LV_HOR_RES, LV_VER_RES);
    lv_obj_set_style_bg_color(register_popup, lv_color_black(), 0);
    lv_obj_set_style_bg_opa(register_popup, LV_OPA_50, 0);
    lv_obj_set_style_border_width(register_popup, 0, 0);
    lv_obj_center(register_popup);
    lv_obj_clear_flag(register_popup, LV_OBJ_FLAG_SCROLLABLE); // 不可滚动

    // 创建登录弹窗
    lv_obj_t * login = lv_obj_create(register_popup);
    lv_obj_set_size(login, 400, 300);
    lv_obj_set_style_radius(login, 12, 0);
    lv_obj_set_style_bg_color(login, lv_color_white(), 0);
    lv_obj_set_style_bg_opa(login, LV_OPA_100, 0);
    lv_obj_set_style_border_width(login, 2, 0);
    lv_obj_set_style_border_color(login, lv_color_hex(0xE0E0E0), 0);
    lv_obj_set_style_shadow_width(login, 20, 0);
    lv_obj_set_style_shadow_opa(login, LV_OPA_30, 0);
    lv_obj_clear_flag(login, LV_OBJ_FLAG_SCROLLABLE); // 不可滚动
    lv_obj_center(login);

    // 添加标题
    lv_obj_t * title = lv_label_create(login);
    lv_label_set_text(title, "注册");
    LV_FONT_DECLARE(SourceHanSansCN_Bold_20);
    lv_obj_set_style_text_font(title, &SourceHanSansCN_Bold_20, LV_PART_MAIN | LV_STATE_DEFAULT);
    lv_obj_set_style_text_color(title, lv_color_hex(0x333333), 0);
    lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 10);
    lv_obj_clear_flag(title, LV_OBJ_FLAG_SCROLLABLE); // 不可滚动

    // 用户名输入框容器
    lv_obj_t * username_cont = lv_obj_create(login);
    lv_obj_set_size(username_cont, 300, 50);
    lv_obj_set_style_bg_opa(username_cont, LV_OPA_0, 0);
    lv_obj_set_style_border_width(username_cont, 0, 0);
    lv_obj_set_style_pad_all(username_cont, 0, 0);
    lv_obj_align(username_cont, LV_ALIGN_TOP_MID, 0, 60);
    lv_obj_clear_flag(username_cont, LV_OBJ_FLAG_SCROLLABLE); // 不可滚动

    // 创建图标
    lv_obj_t * username_icon = lv_img_create(username_cont);
    lv_img_set_src(username_icon, "S:res/ui/username.png");
    lv_obj_set_size(username_icon, 48, 48);
    lv_obj_set_pos(username_icon, 2, 2);

    // 创建输入框
    username_ta1 = lv_textarea_create(username_cont);
    lv_obj_set_size(username_ta1, 250, 48);                                      // 宽度调整
    lv_obj_align_to(username_ta1, username_icon, LV_ALIGN_OUT_RIGHT_MID, 10, 0); // 在图标右边10px
    lv_obj_set_style_radius(username_ta1, 6, 0);
    lv_obj_set_style_border_width(username_ta1, 1, 0);
    lv_obj_set_style_border_color(username_ta1, lv_color_hex(0xCCCCCC), 0);
    lv_obj_set_pos(username_ta1, 50, 0);
    lv_textarea_set_max_length(username_ta1, 20); // 最大长度

    // 密码输入框容器
    lv_obj_t * password_cont = lv_obj_create(login);
    lv_obj_set_size(password_cont, 300, 50);
    lv_obj_set_style_bg_opa(password_cont, LV_OPA_0, 0);
    lv_obj_set_style_border_width(password_cont, 0, 0);
    lv_obj_set_style_pad_all(password_cont, 0, 0);
    lv_obj_align(password_cont, LV_ALIGN_TOP_MID, 0, 130);
    lv_obj_clear_flag(password_cont, LV_OBJ_FLAG_SCROLLABLE); // 不可滚动

    lv_obj_t * password_icon = lv_img_create(password_cont);
    lv_img_set_src(password_icon, "S:res/ui/password.png");
    lv_obj_set_size(password_icon, 48, 48);
    lv_obj_set_pos(password_icon, 2, 2);

    password_ta1 = lv_textarea_create(password_cont);
    lv_obj_set_size(password_ta1, 250, 48);
    lv_obj_align_to(password_ta1, password_icon, LV_ALIGN_OUT_RIGHT_MID, 10, 0); // 在图标右边10px
    lv_obj_set_style_radius(password_ta1, 6, 0);
    lv_obj_set_style_border_width(password_ta1, 1, 0);
    lv_obj_set_style_border_color(password_ta1, lv_color_hex(0xCCCCCC), 0);
    lv_obj_set_pos(password_ta1, 50, 0);
    lv_textarea_set_max_length(password_ta1, 20); // 最大长度

    // 返回按钮
    lv_obj_t * back_btn = lv_btn_create(login);
    lv_obj_set_size(back_btn, 80, 45);

    lv_obj_align(back_btn, LV_ALIGN_BOTTOM_MID, -100, -10);
    lv_obj_set_style_radius(back_btn, 8, 0);
    lv_obj_set_style_bg_color(back_btn, lv_color_hex(0x9E9E9E), 0);

    // 返回按钮文本
    lv_obj_t * back_label = lv_label_create(back_btn);
    lv_label_set_text(back_label, "返回");
    LV_FONT_DECLARE(SourceHanSansCN_Bold_20);
    lv_obj_set_style_text_font(back_label, &SourceHanSansCN_Bold_20, LV_PART_MAIN | LV_STATE_DEFAULT);
    lv_obj_set_style_text_color(back_label, lv_color_white(), 0);
    lv_obj_center(back_label);

    // 确认按钮
    lv_obj_t * confirm_btn = lv_btn_create(login);
    lv_obj_set_size(confirm_btn, 80, 45);

    lv_obj_align(confirm_btn, LV_ALIGN_BOTTOM_MID, 100, -10);
    lv_obj_set_style_radius(confirm_btn, 8, 0);
    lv_obj_set_style_bg_color(confirm_btn, lv_color_hex(0x2196F3), 0);

    // 确认按钮文本
    lv_obj_t * confirm_label = lv_label_create(confirm_btn);
    lv_label_set_text(confirm_label, "确认");
    LV_FONT_DECLARE(SourceHanSansCN_Bold_20);
    lv_obj_set_style_text_font(confirm_label, &SourceHanSansCN_Bold_20, LV_PART_MAIN | LV_STATE_DEFAULT);
    lv_obj_set_style_text_color(confirm_label, lv_color_white(), 0);
    lv_obj_center(confirm_label);

    // 添加键盘
    kb = lv_keyboard_create(register_popup);
    lv_obj_set_size(kb, LV_HOR_RES, LV_VER_RES / 2);
    lv_obj_align(kb, LV_ALIGN_BOTTOM_MID, 0, 0);
    lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN); // 初始隐藏

    // 为文本框添加事件回调
    lv_obj_add_event_cb(username_ta1, ta_event_cb, LV_EVENT_ALL, kb);
    lv_obj_add_event_cb(password_ta1, ta_event_cb, LV_EVENT_ALL, kb);

    // 添加事件
    lv_obj_add_event_cb(confirm_btn, confirm_btn_event, LV_EVENT_CLICKED, register_popup);
    lv_obj_add_event_cb(register_popup, close_login_event, LV_EVENT_CLICKED, register_popup);
    lv_obj_add_event_cb(back_btn, close_register_event, LV_EVENT_CLICKED, register_popup);
}

// 关闭登录窗口事件
static void close_login_event(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        uint32_t current_time = lv_tick_get();
        lv_obj_t * overlay    = (lv_obj_t *)lv_event_get_user_data(e);

        // 检查时间间隔
        if(current_time - last_click_time > 300) {
            clicked = 0; // 超过300ms，重置计数
        }

        clicked++;
        last_click_time = current_time;

        // 如果是第二次点击且在时间窗口内，认为是双击
        if(clicked == 2) {

            clicked = 0;

            if(overlay) {
                lv_obj_del(overlay);
            }
        }
    }
}

static void register_btn_event(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        lv_obj_t * login_scr = lv_event_get_user_data(e);
        register_init(login_scr);
    }
}

static void close_register_event(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        lv_obj_t * overlay = (lv_obj_t *)lv_event_get_user_data(e);
        lv_obj_del(overlay);
    }
}

// 登录按钮事件
static void login_btn_event(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);

    if(code == LV_EVENT_CLICKED) {
        const char * username = lv_textarea_get_text(username_ta);
        const char * password = lv_textarea_get_text(password_ta);

        // 构建 JSON 格式的请求字符串
        char * json_request = build_json_request("login", username, password);
        if(json_request == NULL) {
            show_msg_box("请求数据构建失败", MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT);
            return;
        }

        send_message_to_server(&server_info, json_request);

        free(json_request);
    }
}

// 注册按钮事件
static void confirm_btn_event(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        // 获取文本框中的用户名和密码（原逻辑不变）
        const char * username = lv_textarea_get_text(username_ta1);
        const char * password = lv_textarea_get_text(password_ta1);

        // 构建 JSON 格式的注册请求
        char * json_request = build_json_request("register", username, password);
        if(json_request == NULL) {
            show_msg_box("请求数据构建失败", MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT);
            return;
        }

        send_message_to_server(&server_info, json_request);

        free(json_request);
    }
}

// 构建 JSON 请求字符串  {"type":"login","userid":"test","password":"123456"}）
static char * build_json_request(const char * cmd_type, const char * username, const char * password)
{
    // 创建 JSON 根对象
    cJSON * root = cJSON_CreateObject();
    if(root == NULL) {
        printf("创建 JSON 对象失败\n");
        return NULL;
    }

    strcpy(user_event.userid, username);

    // 向 JSON 对象添加字段
    cJSON_AddStringToObject(root, "type", cmd_type);
    cJSON_AddStringToObject(root, "userid", username ? username : ""); // 避免 NULL 指针
    cJSON_AddStringToObject(root, "password", password ? password : "");

    // 将 JSON 对象转换为字符串
    char * json_str = cJSON_Print(root);

    //  释放 JSON 对象
    cJSON_Delete(root);

    return json_str;
}

// void show_network_connection_title(lv_obj_t * parent)
// {
//     connted_title_card = lv_obj_create(parent);
//     lv_obj_set_size(connted_title_card, 100, 50);
//     lv_obj_align(connted_title_card, LV_ALIGN_TOP_RIGHT, -10, 10);
//     lv_obj_remove_style_all(connted_title_card); // 清除所有样式（实现透明）
//     lv_obj_set_style_pad_all(connted_title_card, 5, 0);
//     lv_obj_clear_flag(connted_title_card, LV_OBJ_FLAG_SCROLLABLE); // 不可滚动
//     // lv_obj_add_flag(connted_title_card, LV_OBJ_FLAG_HIDDEN);

//     connted_title = lv_label_create(connted_title_card);
//     lv_obj_set_style_text_font(connted_title, &SourceHanSansCN_Bold_20, LV_PART_MAIN | LV_STATE_DEFAULT);
//     lv_obj_set_style_text_color(connted_title, lv_color_hex(BLACK), 0);
//     lv_obj_center(connted_title);
//     lv_label_set_text(connted_title, "");
// }